package tools

import (
	"errors"

	"github.com/hashicorp/consul/api"
	"github.com/micro/plugins/v5/registry/consul"
	"github.com/micro/plugins/v5/registry/etcd"
	"github.com/micro/plugins/v5/registry/nacos"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"go-micro.dev/v5/registry"
)

/**
 * 获取go-micro服务实例信息
 *
 * @param string serviceName --------------------------------------必传
 * @author huwl
 * @return string, error
 * @date 2025/08/10 13:31:35
 */
func GetGoMicroServiceInstances(serviceName string) (string, error) {
	var registryInstance registry.Registry

	//获取consul、nacos、etcd配置信息
	config, err := GetConfig(ServiceDiscovery, "yml")
	if err != nil {
		return "", errors.New("读取" + ServiceDiscovery + "配置中心错误：" + err.Error())
	}

	switch ServiceDiscovery {
	case "consul":
		//集成consul
		registryInstance = consul.NewRegistry(
			registry.Addrs(config.GetStringSlice(Env+".addrs")...),
			consul.Config(&api.Config{
				Token: config.GetString(Env + ".secret_id"),
			}),
		)

	case "nacos":
		//集成nacos
		registryInstance = nacos.NewRegistry(func(op *registry.Options) {
			op.Addrs = config.GetStringSlice(Env + ".addrs")
		}, nacos.WithClientConfig(constant.ClientConfig{
			NamespaceId: config.GetString(Env + ".name_space_id"),
			Username:    config.GetString(Env + ".username"),
			Password:    config.GetString(Env + ".password"),
		}))

	case "etcd":
		//集成etcd
		registryInstance = etcd.NewRegistry(func(op *registry.Options) {
			//地址
			op.Addrs = config.GetStringSlice(Env + ".addrs")
			//密码
			// etcd.Auth("gangan", "123")
		}, etcd.Auth(config.GetString(Env+".username"), config.GetString(Env+".password")))
	}

	// 获取服务
	services, err := registryInstance.GetService(serviceName)
	if err != nil {
		return "", errors.New("获取服务失败：" + err.Error())
	}

	if len(services) == 0 {
		return "", errors.New("未找到服务：" + err.Error())
	}

	var address string
	for _, service := range services {
		for _, node := range service.Nodes {
			address = node.Address
		}
	}

	return address, nil
}
